package com.yuyu.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 反射工具类
 *
 * @author yuyu
 * @date 2018/10/19
 */
public final class ReflectionUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);

    /**
     * 创建实例
     *
     * @param cls 类
     */
    public static Object newInstance(Class<?> cls) {
        Object obj;
        try {
            obj = cls.newInstance();
        } catch (Exception e) {
            LOGGER.error("创建实例失败", e);
            throw new RuntimeException(e);
        }
        return obj;
    }

    public static Object invokeMethod(Object obj, Method method, Object... args) {
        Object result;
        try {
            method.setAccessible(true);
            result = method.invoke(obj, args);
        } catch (Exception e) {
            LOGGER.error("初始化方法失败", e);
            throw new RuntimeException(e);
        }
        return result;
    }

    public static void setField(Object obj,Field field,Object value){
        try{
            field.setAccessible(true);
            field.set(obj,value);
        }catch (Exception e){
            LOGGER.error("设置成员变量失败", e);
            throw new RuntimeException(e);
        }
    }


}
